package com.yungu.swift.admin.base;

import com.google.common.collect.Lists;
import com.yungu.swift.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author : cuixiuyin
 * @date : 2019/6/25
 */
@WebFilter(urlPatterns = {"/admin/*"})
public class HttpServletRequestFilter implements Filter {

    private static final List<String> EXCLUDE_URLS = Lists.newArrayList(
            "/admin/v1/common/*/upload", "/admin/v1/operation/*/import",
            "/admin/v1/operation/*/uploadPictures", "/admin/v1/marketing/coupon/gift/uploadCdkey"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            if (!isMatch(EXCLUDE_URLS, httpServletRequest.getRequestURI())) {
                ServletRequest requestWrapper = new HttpServletRequestWrapper(httpServletRequest);
                filterChain.doFilter(requestWrapper, servletResponse);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private Boolean isMatch(List<String> patterns, String url) {
        Boolean flag = false;
        if (!CollectionUtils.isEmpty(patterns)) {
            PathMatcher matcher = new AntPathMatcher();
            for (String pattern : patterns) {
                if (StringUtils.isNotEmpty(pattern) && matcher.match(pattern, url)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    @Override
    public void destroy() {

    }
}
